<template>
    <div class="index-conntainer">
        <div class="head-card">
            <div class="head-card-content">
                <div class="toolBox">
                    <div class="tool_item">
                        <el-row>
                            <el-button type="primary" color="#283C4F" :icon="Refresh" @click="freashBtn" />
                            <el-button type="success" color="#18A0FF" style="color: #FFF;" @click="showmodel">+
                                添加</el-button>
                            <el-button color="#626aef" :dark="isDark" :icon="Delete" @click="checkDel">删除</el-button>
                        </el-row>
                    </div>
                    <div class="tool_itemT">
                        <el-form-item label="" prop="sname" style="width: 150px; margin-right: 10px;">
                            <el-input type="text" v-model="searchval" placeholder="搜索景区名称" />
                        </el-form-item>
                        <el-form-item label="" prop="sname" style="width: 150px; margin-right: 10px;">
                            <el-input type="text" v-model="seaddress" placeholder="搜索景区地址" />
                        </el-form-item>
                        <el-row>
                            <el-button :icon="Search" circle @click="searchBtn" />
                        </el-row>

                    </div>
                </div>
                <div class="listBox">
                    <el-table :data="tableData.slice((currentPage4 - 1) * pageSize4, currentPage4 * pageSize4)" stripe
                        style="width: 100%" max-height="510" header-align="center" v-loading="loading"
                        ref="multipleTableRef" row-key="id" :header-cell-style="{ textAlign: 'center' }" :cell-style="{ textAlign: 'center' }">
                        <el-table-column type="selection" width="105" header-align="center" reserve-selection/>
                        <el-table-column prop="id" label="ID" sortable width="250" header-align="center" />
                        <el-table-column prop="name" label="景区名称" width="250" header-align="center" />
                        <el-table-column prop="region" label="景区地址" width="250" header-align="center" />
                        <el-table-column label="景区图片" width="240">
                            <template #default="scope">
                                <el-image style="width: 100px; height: 80px; padding: 5px;" :src="scope.row.img"
                                    :zoom-rate="1.2" :max-scale="7" :min-scale="0.2" :preview-src-list="[scope.row.img]"
                                    :initial-index="4" fit="cover" preview-teleported="true"/>
                            </template>
                        </el-table-column>
                        <el-table-column property="time" label="创建时间" width="220" header-align="center" />
                        <el-table-column property="address" label="操作" show-overflow-tooltip header-align="center"
                            width="220" v-slot="scope">
                            <el-button type="success" @click="editBtn(scope.row.id)">编辑</el-button>
                            <el-button type="danger" @click="delmodel(scope.row.id)">删除</el-button>
                        </el-table-column>
                    </el-table>
                </div>

                <div class="pageBox">
                    <el-pagination v-model:current-page="currentPage4" v-model:page-size="pageSize4"
                        :page-sizes="[5, 10, 15, 20]" :small="small" :disabled="disabled" :background="background"
                        layout="total, sizes, prev, pager, next, jumper" :total=tableDatalen @size-change="handleSizeChange"
                        :current-page="currentPage4" @current-change="handleCurrentChange" />
                </div>
            </div>
        </div>
        <div class="modelbg" v-show="modelshow">
            <div class="modelbox">
                <!-- 弹窗标题 -->
                <div class="model_title">
                    <div>添加</div>
                    <span @click="closeModel">x</span>
                </div>
                <!-- 弹窗主体 -->
                <div class="model_content">
                    <el-form-item label="景区名称" prop="pass">
                        <el-input type="text" v-model="sname" />
                        <div class="grayText">填写景区名称</div>
                    </el-form-item>

                    <el-form-item label="景区地区" prop="pass">
                        <el-input type="text" v-model="saddress" />
                        <div class="grayText">填写景区地区</div>
                    </el-form-item>

                    <el-form-item label="景区位置" prop="pass">
                        <el-input type="text" autocomplete="off" v-model="slog" placeholder="经度" />
                        <div style="height: 5px;">&nbsp;</div>
                        <el-input type="text" autocomplete="off" v-model="slat" placeholder="纬度" />
                    </el-form-item>
                    <el-form-item label="景区图片" prop="pass" style="display: flex; align-items: center;">
                        <el-input type="text" autocomplete="off" v-model="simg" style="width: 440px;" />
                        <el-upload ref="upload" class="upload-demo" :limit="1" :on-exceed="handleExceed"
                            :auto-upload="false" style="display: flex; align-items: center;" :on-change="handleChange">
                            <template #trigger>
                                <el-button type="primary" :icon="Point">选择</el-button>
                            </template>
                            <el-button class="ml-3" type="success" @click="imgDates" :icon="Position">
                                上传
                            </el-button>
                        </el-upload>
                    </el-form-item>
                    <div class="yimgbox">
                        <div class="demo-image">
                            <div v-for="fit in fits" :key="fit" class="block">
                                <el-image style="width: 100px; height: 100px" :src="url" :fit="fit" />
                            </div>
                        </div>
                    </div>
                    <div style="border: 1px solid #ccc;margin:10px 0;">
                        <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig"
                            :mode="mode" />
                        <Editor style="height: 500px; overflow-y: hidden;" v-model="valueHtml" :defaultConfig="editorConfig"
                            :mode="mode" @onCreated="handleCreated" />
                    </div>
                    <div class="addBtn">
                        <el-button type="success" color="#18A0FF" style="color: #FFF;" @click="addbtn" v-show="btnshow">+
                            添加</el-button>
                        <el-button type="success" color="#67C23A" style="color: #FFF;" @click="editup"
                            v-show="btnshows">确认编辑</el-button>
                    </div>
                </div>
            </div>

        </div>
        <el-dialog v-model="centerDialogVisible" title="危险" width="30%" center>
            <span>
                是否删除此景区信息？
            </span>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="centerDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="sureDel()">
                        确认
                    </el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>
  
<script setup>
import { ref, computed, reactive, onBeforeMount, onBeforeUnmount, shallowRef, onMounted } from 'vue';
import { useI18n } from 'vue-i18n';
import { useStore } from 'vuex';
import { ArrowLeft, ArrowRight, Check, Delete, Edit, Message, Position, Refresh, Right, Search, Star, TopLeft } from '@element-plus/icons-vue'
// import  { UploadInstance } from 'element-plus'
import { genFileId } from 'element-plus'
import { ElTable } from 'element-plus'
import 'vant/lib/index.css';
import { dataList, editDate, imgDate, listAdd, listedit, listdel, listsearch } from '@/api/senice';
import { Left, Point } from '@icon-park/vue-next';
// 富文本引入
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
// 分页组件变量
const currentPage4 = ref(1)
const pageSize4 = ref(5)
const small = ref(false)
const background = ref(true)
const disabled = ref(false)
// 刷新组件变量
const loading = ref(false)
// 表格/列表数据
const tableData = ref([])
const tableDatalen = ref()


// 景区参数
const sname = ref();
const saddress = ref();
const slog = ref();
const slat = ref();
const simg = ref();

// 图片上传预览
const fits = ['contain']
const url = ref()

const uploadRef = ref()
const fileList = ref([]);

const imgtext = ref();

const imgdata = ref({
    name: '',
    file: null
})

// 弹窗操作参数
const modelshow = ref(false);
const btnshow = ref(false)
const btnshows = ref(false)
// 删除弹窗操作参数
const centerDialogVisible = ref(false)
// 获取表格复选框id
const multipleTableRef = ref()
let delsta = 0;

// 搜索功能参数
const searchval = ref()
const seaddress = ref()
// 列表渲染
const ondataList = () => {
    dataList().then((res) => {
        console.log(res);
        let datas = []
        datas = res.data
        let imgs = ''
        // for (let item of datas) {
        //     imgs = item.img.slice(0, 5) + item.img.slice(6)
        //     item.img = item.img.slice(0, 4) + item.img.slice(5)
        // }
        tableData.value = datas
        console.log(tableData.value);
        tableDatalen.value = tableData.value.length
    });
};
// 请求用的，不知道干啥用的
onBeforeMount(() => {
    ondataList();
});


// 刷新按钮
let freashBtn = () => {
    clearParam()
    console.log(6666);
    loading.value = true;
    setTimeout(() => {
        loading.value = false;
    }, 1000)
    dataList().then((res) => {
        console.log(res);
        let datas = []
        datas = res.data
        let imgs = ''
        for (let item of datas) {
            imgs = item.img.slice(0, 5) + item.img.slice(6)
            item.img = item.img.slice(0, 4) + item.img.slice(5)
        }
        tableData.value = datas
        tableDatalen.value = tableData.value.length
    });
}
// 列表数据初始化
function clearParam() {
    sname.value = ''
    saddress.value = ''
    slog.value = ''
    slat.value = ''
    simg.value = ''
    valueHtml.value = ''
    url.value = ''
}



// 添加/编辑 弹窗操作
let showmodel = () => {
    console.log(modelshow.value);
    clearParam()
    btnshow.value = true;
    btnshows.value = false;
    if (modelshow.value == true) {
        modelshow.value = false
    } else {
        modelshow.value = true
    }
}

// 编辑景区按钮
// 编辑回显
const snid = ref();
let editBtn = (sid) => {
    snid.value = sid;
    btnshow.value = false;
    btnshows.value = true;
    clearParam()
    console.log(sid);
    console.log(modelshow.value);
    if (modelshow.value == true) {
        modelshow.value = false
    } else {
        modelshow.value = true
    }
    editDate({ scienceid: sid }).then((res) => {
        console.log(res);

        if (res.status == 1) {
            sname.value = res.data.sciencename
            saddress.value = res.data.region
            slog.value = res.data.longitude
            slat.value = res.data.latitude
            simg.value = res.data.img
            valueHtml.value = res.data.content
            url.value = `http://scienicpc.kuxia.top/${simg.value}`
        } else {
            modelshow.value = false
            ElNotification({
                title: 'Error',
                message: res.err,
                type: 'error',
            })
        }
    });
}
// 确认编辑
let editup = () => {
    let editdata = {
        scienceid: snid.value,
        name: sname.value,
        region: saddress.value,
        longitude: slog.value,
        latitude: slat.value,
        img: simg.value,
        content: valueHtml.value
    }
    console.log(editdata);
    let nullis = 0;
    for (let key in editdata) {
        if (editdata[key] != undefined) {
            nullis++
        }
    }
    console.log(nullis);
    if (nullis == 7) {
        listedit(editdata).then((res) => {
            console.log(res);
            if (res.status == 1) {
                ElNotification({
                    title: 'Success',
                    message: '编辑成功',
                    type: 'success',
                })
                modelshow.value = false;
                freashBtn()
            } else {
                ElNotification({
                    title: 'Error',
                    message: '编辑失败，请稍后重试',
                    type: 'error',
                })
            }
        });
    } else {
        ElNotification({
            title: 'Error',
            message: '请完善景区信息',
            type: 'error',
        })
    }
}
// 弹窗关闭按钮
let closeModel = () => {
    modelshow.value = false
}


const handleChange = (file, filelist) => {
    console.log(file);
    imgdata.value.file = file.raw
    imgdata.value.name = file.name
    console.log(imgdata.value);
}
// 图片上传
const imgDates = () => {
    // 此时可以自行将文件上传至服务器
    console.log(imgdata);
    if (imgdata.value.file == null) {
        return;
    }
    let param = new FormData();
    //创建form对象
    param.append('img', imgdata.value.file, imgdata.value.name); //通过append向form对象添加数据
    console.log(param);
    imgDate(param).then((res) => {
        console.log(res);
        simg.value = res.front_file
        url.value = `http://scienicpc.kuxia.top/${simg.value}`
        console.log(url);
    });
}
// 确认添加按钮
let addbtn = () => {
    let addDatas = {
        name: sname.value,
        region: saddress.value,
        longitude: slog.value,
        latitude: slat.value,
        img: simg.value,
        content: valueHtml.value
    }
    console.log(addDatas);
    let nullis = 0;
    for (let key in addDatas) {
        if (addDatas[key] != undefined) {
            nullis++
        }
    }
    console.log(nullis);
    if (nullis == 6) {
        listAdd(addDatas).then((res) => {
            console.log(res);
            ElNotification({
                title: 'Success',
                message: '添加成功',
                type: 'success',
            })
            modelshow.value = false;
            freashBtn()
        });
    } else {
        ElNotification({
            title: 'Error',
            message: '请完善景区信息',
            type: 'error',
        })
    }

}

// 删除操作（列表删除按钮）
const delid = ref();
let delmodel = (delids) => {
    centerDialogVisible.value = true
    delid.value = delids
    delsta = 1;
}
let sureDel = () => {
    centerDialogVisible.value = false
    console.log(delid.value);
    if (delsta == 1) {
        listdel({ scienceid: delid.value }).then((res) => {
            console.log(res);
            if (res.status == 1) {
                ElNotification({
                    title: 'Success',
                    message: '删除成功',
                    type: 'success',
                })
                freashBtn();
            } else {
                ElNotification({
                    title: 'Error',
                    message: '删除失败，请稍后重试',
                    type: 'error',
                })
            }
        })
        console.log(arrData);
        console.log(delsta);
    } else {
        let arrData = [];
        multipleTableRef.value.getSelectionRows().map((item) => {
            arrData.push(item.id)
        })
        if (arrData.length >= 1) {
            listdel({ scienceid: arrData }).then((res) => {
                console.log(res);
                if (res.status == 1) {
                    ElNotification({
                        title: 'Success',
                        message: '删除成功',
                        type: 'success',
                    })
                    freashBtn();
                } else {
                    ElNotification({
                        title: 'Error',
                        message: '删除失败，请稍后重试',
                        type: 'error',
                    })
                }
            })
        } else {
            ElNotification({
                title: 'Error',
                message: '请选择要删除的数据',
                type: 'error',
            })
        }

    }
}
let checkDel = () => {
    centerDialogVisible.value = true
    delsta = 2
    console.log(delsta);
}

// 富文本
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()

// 内容 HTML
const valueHtml = ref('<p>hello</p>')

// 模拟 ajax 异步获取内容
onMounted(() => {
    setTimeout(() => {
        valueHtml.value = '<p>请输入景点介绍</p>'
    }, 1500)
})

const toolbarConfig = {}
const editorConfig = { placeholder: '请输入内容...' }

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
    const editor = editorRef.value
    if (editor == null) return
    editor.destroy()
})

const handleCreated = (editor) => {
    editorRef.value = editor // 记录 editor 实例，重要！
}

// 搜索功能
let searchBtn = () => {
    if (searchval.value != undefined || seaddress.value != undefined) {
        let searchobj = {
            sciencename: searchval.value,
            region: seaddress.value
        }
        listsearch(searchobj).then((res) => {
            console.log(res);
            tableData.value = res.data
        })
    } else {
        ElNotification({
            title: 'Error',
            message: '请输入搜索内容',
            type: 'error',
        })
    }
}



// 分页功能实现
// const handleSizeChange = () => {
//   console.log(`${val} items per page`)
// }
// const handleCurrentChange = () => {
//   console.log(`current page: ${val}`)
// }


</script>

<style lang="scss" scoped>
.head-card {
    padding: $base-main-padding;
    background-color: $base-color-white;
}

.toolBox {
    width: 100%;
    height: 50px;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.tool_item {
    height: 100%;
    display: flex;
    flex-wrap: wrap;
    align-items: center;
}

.tool_itemT {
    width: 40%;
    height: 100%;
    display: flex;
    flex-wrap:nowrap;
    justify-content: right;
}

.search_inp {
    border: 1px solid #DCDFE6;
    padding-left: 10px;
    border-radius: 5px;
}

.listBox {
    width: 100%;
    height: 520px;
}

.pageBox {
    width: 100%;
    height: 50px;
    display: flex;
    align-items: center;
    // justify-content: space-around;
}

.demo-pagination-block+.demo-pagination-block {
    margin-top: 10px;
}

.demo-pagination-block .demonstration {
    margin-bottom: 16px;
}

// 弹窗样式
.modelbg {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba($color: #000000, $alpha: 0.4);
    z-index: 10;

}

.modelbox {
    width: 900px;
    height: 600px;
    background-color: #FFFFFF;
    margin: 10% 30%;
}

.model_title {
    background-color: #283C4F;
    color: #FFFFFF;
    padding: 15px;
    display: flex;
    justify-content: space-between;
}

.model_title>div {
    cursor: default
}

.model_title>span {
    cursor: pointer
}

.model_content {
    width: 80%;
    padding: 20px 0 0 30px;
    margin: 0 5%;
    height: 496px;
    margin-right: 10px;
    // display: flex;
    // align-items: center;
    overflow: scroll;
}

// 输入框样式
.staff_item {
    width: 80%;
    height: 12.5%;
    margin-bottom: 20px;
    display: flex;

}

.staffItem_name {
    width: 10%;
    height: 100%;
    font-size: 15px;
    color: #606266;
    display: flex;
    justify-content: center;
    align-items: center;
}

.staffItem_name>span {
    color: red;
}

.input_staff {
    width: 100%;
    height: 30px;
    border: 1px solid #DCDFE6;
    border-radius: 5px;
    padding: 0 10px;
    margin-top: 10px;
}

.staffBox {
    width: 90%;
    height: 30px;
}

.input_staff>input {
    height: 100%;
    width: calc(100%-10px);
    border: none;
    outline: none;
}

.input_staff>img {
    width: 16px;
    height: 16px;
    transition: 0.2s;
}

.staff_massage {
    font-size: 12px;
    color: #F56C6C;
    display: none;
}

.grayText {
    color: #C6B4AE;
    font-size: 14px;
}

// 图片上传预览样式
.yimgbox {
    height: 100px;
    width: 120px;
    border: 1px solid #EBEBEB;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-left: 70px;
    margin-top: -10px;
}

.demo-image .block {
    text-align: center;
    border-right: solid 1px var(--el-border-color);
    display: inline-block;
    width: 20%;
    box-sizing: border-box;
    vertical-align: top;
}

.demo-image .block:last-child {
    border-right: none;
}

.demo-image .demonstration {
    display: block;
    color: var(--el-text-color-secondary);
    font-size: 14px;
    margin-bottom: 20px;
}

.addBtn {
    width: 100%;
    display: flex;
    justify-content: right;
}
</style>
  